package com.buba.controller;

import cn.hutool.json.JSONObject;
import com.buba.mapper.FriendMapper;
import com.buba.mapper.MessageMapper;
import com.buba.service.MessageService;
import entity.Friend;
import org.springframework.web.bind.annotation.*;
import result.CommonResult;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @descriptions: 聊天记录
 * @author: ZQ
 * @date: 2023/2/16 14:00
 */
@RestController
@RequestMapping("/message")
public class MessageController {

    @Resource
    private MessageMapper messageMapper;
    @Resource
    private FriendMapper friendMapper;
    @Resource
    private MessageService messageService;

    /**
     * @descriptions 获取用户消息
     * @author ZQ
     * @date 2023/3/1 14:33
     * @param myId
     * @param friendId
     * @return result.CommonResult
     */
    @GetMapping("/readMessage")
    public CommonResult readMessage(Integer myId, Integer friendId){
        // 判断myId friendId 是否为null 是否为0
        if (myId != null && myId != 0 && friendId != null && friendId != 0) {
            // 根据myId,friendId 查询好友信息
            Friend friend = friendMapper.getFriend(myId, friendId);
            // 判断friend是否为空
            if (friend != null) {
                // 根据sessionId 查找聊天记录
                List<Map> messageList = messageMapper.readMessage(friend.getSessionId());
                // 判断messageList是否为空
                if (messageList != null){
                    // messageList不为空返回数据
                    return CommonResult.ok(messageList);
                } else {
                    // messageList为空 返回结果
                    return CommonResult.fail("没有聊天信息");
                }
            } else {
                // friend为空 返回结果
                return CommonResult.fail("没有此信息");
            }
        } else {
            // 判断条件为false返回结果
            return CommonResult.fail("空");
        }
    }

    /**
     * @descriptions 保存聊天记录
     * @author ZQ
     * @date 2023/3/1 14:34
     * @param param
     * @return result.CommonResult
     */
    @PostMapping("/saveMessageRecord")
    public CommonResult saveMessageRecord(@RequestBody Map<String,String> param) {
        // 判断param是否为空
        if (param != null) {
            // 取值
            String sender = param.get("sender");
            String persons = param.get("persons");
            String msg = param.get("msg");
            // 保存聊天记录
            messageService.storeMessage(sender, persons, msg , "text");
            // 返回结果
            return CommonResult.ok("保存成功");
        } else {
            // param为空返回结果
            return CommonResult.fail("param为空");
        }
    }

}